package ru.digitanoise.dnaccountapi.services;

import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ru.digitanoise.dnaccountapi.api.internal.service.InternalApiService;
import ru.digitanoise.dnaccountapi.models.entity.Account;
import ru.digitanoise.dnaccountapi.repositorys.AccountRepository;
import ru.digitanoise.dnutils.exception.ApiException;

@Service
@RequiredArgsConstructor
public class AccountService {

    private final AccountRepository accountRepository;
    private final InternalApiService internalApiService;

    @Transactional
    public Account saveAccount(Account account, MultipartFile file) throws ApiException {
        if (file != null) {
            account.setUriAvatar(internalApiService.saveImage(file));
        }
        accountRepository.save(account);

        String code = internalApiService.generateCode(account.getId());
        internalApiService.sendEmailActive(account.getEmail(), code);

        return account;
    }

    public Account getAccountById(Long accountId) {
        return accountRepository.findById(accountId).orElseThrow(
                () -> new ApiException("Not found account with id: " + accountId)
        );
    }

    @Transactional
    public void accountActive(String codeActive) {
        Long accountId  = internalApiService.validActiveCode(codeActive);
        Account account = getAccountById(accountId);
        account.setActive(true);
        accountRepository.save(account);
    }

}
